<template>
  <div class="user-search-container">
    <!-- 排序选项 -->
    <div class="filter-section">
      <div class="sort-options">
        <div
          v-for="option in sortOptions"
          :key="option.value"
          :class="['btn-filter', { active: currentSort === option.value }]"
          @click="changeSort(option.value)"
        >
          <span class="sort-icon">{{ option.icon }}</span>
          {{ option.label }}
        </div>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div class="search-results">
      <div class="result-count" v-if="totalCount">
        共找到
        <span class="highlight-count">{{ totalCount }}</span>
        个相关用户
        <span class="kawaii-emoji">ヾ(≧∀≦*)ﾉ</span>
      </div>

      <!-- 用户列表 -->
      <div class="user-list" v-if="!loading || users.length > 0">
        <div
          v-for="user in users"
          :key="user.id"
          class="user-card"
          @click="goToUserSpace(user.id)"
        >
          <div class="user-avatar-container">
            <img :src="user.avatar" class="user-avatar" alt="用户头像" />
          </div>
          <div class="user-info">
            <div
              class="user-name"
              v-html="highlightKeyword(user.nickname)"
            ></div>
            <div class="user-signature">{{ user.signature }}</div>
            <div class="user-stats">
              <div class="stat-item">
                <span class="stat-icon">🎬</span>
                <span class="stat-count">
                  {{ formatCount(user.videoCount) }}
                </span>
                <span class="stat-label">投稿</span>
              </div>
              <div class="stat-item">
                <span class="stat-icon">👥</span>
                <span class="stat-count">{{ formatCount(user.fans) }}</span>
                <span class="stat-label">粉丝</span>
              </div>
              <div class="stat-item">
                <span class="stat-icon">❤️</span>
                <span class="stat-count">{{ formatCount(user.likes) }}</span>
                <span class="stat-label">获赞</span>
              </div>
            </div>
            <div class="user-tags" v-if="user.tags && user.tags.length">
              <span
                v-for="(tag, index) in user.tags"
                :key="index"
                class="user-tag"
              >
                {{ tag }}
              </span>
            </div>
          </div>
          <div
            class="follow-btn"
            :class="{ 'is-followed': user.isFollowed }"
            @click.stop="toggleFollow(user)"
          >
            {{ user.isFollowed ? '已关注' : '关注' }}
          </div>
        </div>
      </div>

      <!-- 加载更多提示 -->
      <div
        class="loading-container"
        ref="loadingRef"
        v-if="!noMoreData && !showNoMoreTip && users.length > 0"
      >
        <div class="loading-spinner" v-if="isLoading"></div>
        <span v-if="isLoading">正在加载更多用户...</span>
      </div>

      <!-- 没有更多数据提示 -->
      <div class="no-more" v-if="noMoreData || showNoMoreTip">
        — 没有更多可爱的用户啦 —
      </div>

      <!-- 空结果提示 -->
      <div class="empty-result" v-if="!loading && users.length === 0">
        <div class="empty-mascot"></div>
        <p class="empty-text">没有找到相关用户</p>
        <p class="empty-suggestion">换个关键词试试吧~</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

// 用户接口定义
interface User {
  id: number | string
  nickname: string
  avatar: string
  level: number
  fans: number
  likes: number
  videoCount: number
  signature: string
  isFollowed: boolean
  tags?: string[]
}

const route = useRoute()
const router = useRouter()

// 搜索数据
const users = ref<User[]>([])
const currentPage = ref(1)
const loading = ref(false)
const noMoreData = ref(false)
const showNoMoreTip = ref(false)
const totalCount = ref(0)
const isLoading = computed(() => loading.value)

// 排序选项
const sortOptions = [
  { label: '综合排序', value: 'comprehensive', icon: '✨' },
  { label: '最多粉丝', value: 'fans', icon: '👥' },
  { label: '最多投稿', value: 'videos', icon: '🎬' },
]

// 当前排序方式
const currentSort = ref('comprehensive')

// 搜索关键词
const searchKeyword = computed(() => {
  const keyword = route.query.keyword as string
  return keyword || ''
})

// 二次元相关用户昵称
const animeNicknames = [
  '樱花飘雪',
  '星空物语',
  '千夜未来',
  '时光守护者',
  '雨中漫步',
  '梦境旅人',
  '幻想使者',
  '樱花祭司',
  '雪之舞者',
  '银月之狼',
  '宇宙猫咪',
  '魔法少女',
  '未来科技',
  '森林守护者',
  '幻想乐园',
  '星辰大海',
  '缥缈幻境',
  '梦想守护者',
  '樱花庄的猫',
  '风铃物语',
  '花开半夏',
  '时光旅行者',
  '云端漫步',
  '森林精灵',
  '星辰旅者',
  '水晶传说',
  '雪花飘舞',
  '花语心愿',
  '月光女神',
  '太阳骑士',
]

// 二次元相关签名
const animeSignatures = [
  '这个人很懒，什么都没有留下...',
  '愿世界和平，愿你我安好~',
  '梦里能飞 心中有爱 追逐动漫的世界',
  '我只是一个路过的假面骑士',
  '热爱动漫的普通高中生一枚',
  '与其在别处仰望 不如在这里并肩',
  '喜欢就是喜欢，哪来的什么理由',
  '愿你被这个世界温柔以待',
  '我们都是星辰大海的追梦人',
  '生命在于体验，而不在于争论',
  '如果有来世，我仍会选择成为二次元爱好者',
  '青春是一场无法回放的绚丽',
  '花开花落，云卷云舒，如此而已',
  '用温柔对抗世界的坚硬',
  '动漫是青春的诗，漫画是岁月的歌',
  '做一个温暖的人，用二次元的快乐治愈疲惫的灵魂',
  '我喜欢的东西，都藏在这里了',
  '愿你有纸片人的颜值，也有三次元的运气',
  '守护每一个二次元的梦想',
  '把喜欢的东西藏进生活的角落',
]

// 二次元相关标签
const animeTags = [
  '动漫控',
  '漫画家',
  '轻小说爱好者',
  'COSER',
  '声优粉',
  '日漫迷',
  '国漫担',
  'MAD制作者',
  '画师',
  '电竞少女',
  '萌新',
  '资深党',
  '宅宅',
  '纸片人控',
  '安利达人',
  '催更小能手',
  '收藏狂魔',
  '表情包制作者',
  'VTuber',
  '同人创作者',
]

// 获取用户数据
const fetchUsers = async () => {
  if (loading.value || noMoreData.value) return

  loading.value = true
  try {
    // 开发阶段使用模拟数据
    await loadMockData()
  } catch (error) {
    console.error('获取搜索结果失败:', error)
  } finally {
    loading.value = false
  }
}

// 模拟数据加载
const loadMockData = () => {
  // 设置总数
  if (currentPage.value === 1) {
    totalCount.value = 35
  }

  // 头像URL数组 - 使用本地anime/avatar目录下的头像
  const avatars = [
    '/src/assets/anime/avatar/avatar1.png',
    '/src/assets/anime/avatar/avatar2.png',
    '/src/assets/anime/avatar/avatar3.png',
    '/src/assets/anime/avatar/avatar4.png',
    '/src/assets/anime/avatar/avatar5.png',
    '/src/assets/anime/avatar/avatar6.png',
    '/src/assets/anime/avatar/avatar7.png',
    '/src/assets/anime/avatar/avatar8.png',
    '/src/assets/anime/avatar/avatar9.png',
    '/src/assets/anime/avatar/avatar10.png',
    '/src/assets/anime/avatar/avatar11.png',
    '/src/assets/anime/avatar/avatar12.png',
    '/src/assets/anime/avatar/avatar13.png',
  ]

  // 创建模拟数据
  const mockUsers: User[] = Array(currentPage.value < 3 ? 10 : 5)
    .fill(0)
    .map((_, index) => {
      // 确保生成正数的随机数
      let fans = Math.floor(Math.random() * 1000000) + 1000
      let likes = Math.floor(Math.random() * 5000000) + 5000
      let videoCount = Math.floor(Math.random() * 200) + 5
      let level = Math.floor(Math.random() * 6) + 1

      // 根据排序方式调整数据
      switch (currentSort.value) {
        case 'fans':
          fans = 1000000 - (currentPage.value - 1) * 50000 - index * 5000
          break
        case 'videos':
          videoCount = 200 - (currentPage.value - 1) * 10 - index * 2
          break
        case 'level':
          level =
            6 -
            Math.floor((currentPage.value - 1) * 0.5) -
            Math.floor(index * 0.2)
          if (level < 1) level = 1
          break
        case 'comprehensive':
        default:
          // 综合排序，前几个结果质量更高
          if (index < 3) {
            fans = Math.floor(Math.random() * 800000) + 200000
            likes = Math.floor(Math.random() * 3000000) + 2000000
            videoCount = Math.floor(Math.random() * 100) + 100
            level = Math.floor(Math.random() * 2) + 5
          }
          break
      }

      // 随机选择用户昵称和签名
      const nicknameIndex = Math.floor(Math.random() * animeNicknames.length)
      const signatureIndex = Math.floor(Math.random() * animeSignatures.length)

      // 随机选择1-2个标签
      const tagCount = Math.floor(Math.random() * 2) + 1
      const tags: string[] = []
      for (let i = 0; i < tagCount; i++) {
        const tagIndex = Math.floor(Math.random() * animeTags.length)
        if (!tags.includes(animeTags[tagIndex])) {
          tags.push(animeTags[tagIndex])
        }
      }

      // 随机选择头像
      const avatarIndex = Math.floor(Math.random() * avatars.length)

      // 创建用户数据
      const id = (currentPage.value - 1) * 10 + index + 1
      let nickname = animeNicknames[nicknameIndex]

      // 可能添加关键词到昵称中
      if (searchKeyword.value && Math.random() > 0.5) {
        nickname = `${nickname}${searchKeyword.value}`
      }

      return {
        id,
        nickname,
        avatar: avatars[avatarIndex],
        level,
        fans,
        likes,
        videoCount,
        signature: animeSignatures[signatureIndex],
        isFollowed: Math.random() > 0.7, // 30%的概率已关注
        tags,
      }
    })

  users.value = [...users.value, ...mockUsers]
  currentPage.value++

  // 第3页后模拟没有更多数据
  if (currentPage.value > 3) {
    noMoreData.value = true
  }

  // 模拟API调用延迟
  return new Promise((resolve) => setTimeout(resolve, 500))
}

// 格式化数字
const formatCount = (count: number): string => {
  if (count >= 10000) {
    return (count / 10000).toFixed(1) + '万'
  }
  return count.toString()
}

// 高亮关键词
const highlightKeyword = (text: string): string => {
  if (!searchKeyword.value) return text

  const keyword = searchKeyword.value
  const regex = new RegExp(keyword, 'gi')
  return text.replace(
    regex,
    (match) => `<span class="highlight">${match}</span>`,
  )
}

// 切换关注状态
const toggleFollow = (user: User) => {
  user.isFollowed = !user.isFollowed

  // 在实际应用中，这里会有API调用
  console.log(`${user.isFollowed ? '关注' : '取消关注'}用户: ${user.nickname}`)
}

// 跳转到用户空间
const goToUserSpace = (userId: number | string) => {
  router.push({
    path: `/front/user/${userId}`,
    query: {
      from: 'search',
      keyword: searchKeyword.value,
    },
  })
}

// 切换排序方式
const changeSort = (sortType: string) => {
  if (currentSort.value === sortType) return

  currentSort.value = sortType

  // 重置数据
  users.value = []
  currentPage.value = 1
  noMoreData.value = false

  // 重新获取数据
  fetchUsers()
}

// 监听搜索关键词变化
watch(
  () => route.query.keyword,
  (newKeyword) => {
    // 重置数据
    users.value = []
    currentPage.value = 1
    noMoreData.value = false
    totalCount.value = 0

    // 重新获取数据
    fetchUsers()
  },
  { immediate: true }, // 确保首次加载时也执行
)

// 初始加载
onMounted(() => {
  if (users.value.length === 0) {
    fetchUsers()
  }
})
</script>

<style lang="scss" scoped>
.user-search-container {
  padding: 0 10px;
}

.filter-section {
  margin-bottom: 20px;
  width: 100%;
  overflow-x: auto;

  &::-webkit-scrollbar {
    height: 4px;
  }

  &::-webkit-scrollbar-track {
    background: #f5f5f5;
    border-radius: 2px;
  }

  &::-webkit-scrollbar-thumb {
    background: #ffb6c1;
    border-radius: 2px;
  }
}

.sort-options {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  padding: 0 10px;

  .btn-filter {
    white-space: nowrap;
    padding: 6px 14px;
    margin-right: 12px;
    border-radius: 16px;
    font-size: 14px;
    color: #7c5479;
    background-color: rgba(255, 255, 255, 0.6);
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid #ffcbe3;
    display: flex;
    align-items: center;

    .sort-icon {
      margin-right: 4px;
      font-size: 14px;
    }

    &:hover {
      background-color: #ffcbe3;
      transform: translateY(-2px);
    }

    &.active {
      background: linear-gradient(to right, #fe4ea4, #ff9fcf);
      color: #fff;
      box-shadow: 0 2px 8px rgba(254, 78, 164, 0.3);
      border-color: transparent;
    }
  }
}

.search-results {
  position: relative;
}

.result-count {
  font-size: 15px;
  color: #7c5479;
  margin-bottom: 20px;

  .highlight-count {
    color: #fe4ea4;
    font-weight: bold;
    font-size: 18px;
    margin: 0 3px;
  }

  .kawaii-emoji {
    margin-left: 5px;
    color: #fe4ea4;
  }
}

.user-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;

  .user-card {
    position: relative;
    display: flex;
    flex-direction: column;
    padding: 20px;
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(254, 78, 164, 0.1);
    transition: all 0.3s;
    cursor: pointer;
    overflow: hidden;
    border: 1px solid rgba(255, 182, 193, 0.3);

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 60px;
      background: linear-gradient(135deg, #ffcbe3, #ffd6ff);
      opacity: 0.5;
      z-index: 0;
    }

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 24px rgba(254, 78, 164, 0.2);
    }

    .user-avatar-container {
      position: relative;
      width: 80px;
      height: 80px;
      margin: 0 auto 10px;
      z-index: 1;

      .user-avatar {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        object-fit: cover;
        border: 3px solid #fff;
        box-shadow: 0 2px 10px rgba(254, 78, 164, 0.2);
      }
    }

    .user-info {
      text-align: center;
      z-index: 1;

      .user-name {
        font-size: 18px;
        font-weight: bold;
        color: #7c5479;
        margin-bottom: 8px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;

        .highlight {
          color: #fe4ea4;
          font-weight: bold;
          background-color: rgba(254, 78, 164, 0.1);
          padding: 0 4px;
          border-radius: 4px;
        }
      }

      .user-signature {
        font-size: 13px;
        color: #99809d;
        margin-bottom: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        min-height: 36px;
      }
    }

    .user-stats {
      display: flex;
      justify-content: center;
      margin-bottom: 12px;

      .stat-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin: 0 10px;

        .stat-icon {
          font-size: 16px;
          margin-bottom: 4px;
        }

        .stat-count {
          font-size: 14px;
          font-weight: bold;
          color: #7c5479;
        }

        .stat-label {
          font-size: 12px;
          color: #99809d;
        }
      }
    }

    .user-tags {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      gap: 6px;
      margin-bottom: 15px;

      .user-tag {
        font-size: 12px;
        color: #7c5479;
        background-color: rgba(255, 182, 193, 0.2);
        border-radius: 10px;
        padding: 2px 8px;
      }
    }

    .follow-btn {
      align-self: center;
      padding: 6px 20px;
      background: linear-gradient(135deg, #fe4ea4, #ff9fcf);
      color: white;
      border-radius: 20px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.2s;
      z-index: 1;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(254, 78, 164, 0.3);
      }

      &.is-followed {
        background: #f0f0f0;
        color: #99809d;

        &:hover {
          background: #ffd6e7;
          color: #fe4ea4;
        }
      }
    }
  }
}

.empty-result {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60px 0;

  .empty-mascot {
    width: 150px;
    height: 150px;
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200"><circle cx="100" cy="100" r="80" fill="%23ffcbe3"/><circle cx="70" cy="80" r="10" fill="%23fff"/><circle cx="130" cy="80" r="10" fill="%23fff"/><path d="M70,120 Q100,140 130,120" stroke="%23fe4ea4" stroke-width="4" fill="none"/></svg>');
    background-size: contain;
    background-position: center;
    background-repeat: no-repeat;
    margin-bottom: 20px;
    animation: float 3s ease-in-out infinite;
  }

  .empty-text {
    font-size: 18px;
    color: #7c5479;
    margin-bottom: 10px;
    font-weight: bold;
  }

  .empty-suggestion {
    font-size: 14px;
    color: #c9a0dc;
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px 0;
  color: #fe4ea4;

  .loading-spinner {
    width: 30px;
    height: 30px;
    border: 3px solid #ffcbe3;
    border-top-color: #fe4ea4;
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
    margin-bottom: 10px;
  }
}

.no-more {
  text-align: center;
  color: #c9a0dc;
  padding: 20px 0;
  position: relative;

  &::before,
  &::after {
    content: '';
    position: absolute;
    top: 50%;
    width: 80px;
    height: 1px;
    background: linear-gradient(to right, transparent, #ffcbe3);
  }

  &::before {
    left: calc(50% - 120px);
  }

  &::after {
    right: calc(50% - 120px);
    transform: rotate(180deg);
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-15px);
  }
}

@media (max-width: 768px) {
  .user-list {
    grid-template-columns: 1fr;
  }
}
</style>
